import router from "@/router";
import store from "@/store";
import { getToken } from "@/utils/common";
import { $session, $store } from "@/utils/store";
import axios from "axios";
import { MessageBox, Notification } from "element-ui";
let flag = false;
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VITE_APP_BASE_API,
  // 超时
  timeout: 600000,
  validateStatus: (status) => {
    // 错误编码为2开头和400报错误提示
    return status >= 200 && status <= 511;
  },
});

/**
 * 设置 Cur-Industry-Code 请求头
 *
 * @param {Object} config - 请求配置对象
 */
function setCurIndustryCodeHeader(config) {
  let industryCode = "";
  if (config && config.url == "/auth/chooseTrade") {
    industryCode = sessionStorage.getItem("chooseTradeVersionddw") || "";
  } else {
    if (sessionStorage.getItem("chooseTradeVersiondd2")) {
      industryCode = sessionStorage.getItem("chooseTradeVersiondd2");
    } else {
      let p = sessionStorage.getItem("chooseTradeVersiondd");
      if (p) {
        p = JSON.parse(p);
        industryCode = p && p.industryCode ? p.industryCode : "";
      }
    }
  }
  return industryCode;
}

/**
 * 请求拦截器
 *
 * @param {Object} config - 请求配置对象
 * @returns {Object} - 修改后的请求配置对象
 */
function requestInterceptors(config) {
  if (getToken()) {
    config.headers["Authorization"] = `Bearer ${getToken()}`;
    config.headers["Cur-Industry-Code"] = setCurIndustryCodeHeader(config);
  }
  config.headers["x-frame-options"] = "SAMEORIGIN";
  return config;
}

/**
 * 处理404错误
 *
 * @param {*} config
 * @param {*} code
 * @param {*} message
 */
function error404(config, code, message) {
  console.log("Http: --> START");
  console.log(`Http: --> ${config.url}`);
  console.log(
    "Http: request 参数",
    config.method.toLowerCase() === "get"
      ? config.params || ""
      : config.data || ""
  );
  console.log(`Http: <-- ${code || ""} ${config.url}`);
  console.log("Http: response", message);
  console.log("Http: <-- END");
}

/**
 * 对响应拦截器进行处理
 *
 * @param res 响应对象
 * @returns 响应数据
 */
function responseInterceptors(res) {
  const msg = res.data.msg || res.data.message; // 网关响应参数可能为msg或message
  if (res.data.code === 401) {
    // 401:token失效
    sessionStorage.clear();
    $store.clear();
    $session.clear();
    if (!flag) {
      flag = true;
      MessageBox.alert(msg + "，请重新联系管理员或重新登录", "系统提示", {
        confirmButtonText: "确定",
        type: "warning",
        callback: () => {
          store.dispatch("FedLogOut").then(() => {
            flag = false;
            router.push({
              path: "/login",
            });
          });
        },
      });
    }
  } else if (res.data.code === 404) {
    error404(res.config, res.data.code, res.data);
    return res.data;
  } else {
    if (res?.config?.responseType === "blob") {
      if (res?.data) {
        return res.data;
      } else {
        Notification.error({
          title: "提示",
          message: "文件下载失败!",
        });
      }
    } else {
      return res.data;
    }
  }
}

// request拦截器
request.interceptors.request.use(
  (config) => {
    return requestInterceptors(config);
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    return responseInterceptors(res);
  },
  (error) => {
    let { message, config } = error;
    let timer;
    if (message === "Network Error") {
      message = "系统接口请求异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      const code = message.substr(message.length - 3);
      if (code === "503") {
        Notification.warning({
          title: "警告",
          message: "服务尚未注册成功,请确认已启动服务后稍等!",
          customClass: "system-notify",
        });
      } else if (code === "601") {
        error601(timer);
      } else if (code === "401") {
        // 401:token失效
        if (!flag) {
          flag = true;
          MessageBox.alert(
            "暂未登录或token已经过期，请重新联系管理员或重新登录",
            "系统提示",
            {
              confirmButtonText: "确定",
              type: "warning",
              callback: () => {
                store.dispatch("FedLogOut").then(() => {
                  flag = false;
                  router.push({
                    path: "/login",
                  });
                });
              },
            }
          );
        }
      } else if (code === "404") {
        error404(config, code, message);
      } else {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
        Notification.error({
          title: "错误",
          message: message,
          customClass: "system-notify",
        });
      }
    } else {
      // other
    }
    return Promise.reject(error);
  }
);

export default request;
